package builder;

import mapping.Configuration;
import mapping.MappedStatement;
import org.dom4j.Element;
import sqlnode.impl.MixedSqlNode;
import sqlsource.SqlSource;
import sqlsource.impl.DynamicSqlSource;
import sqlsource.impl.RawSqlSource;
import utils.ResolveType;

/*
 * @auther 顶风少年
 * @mail dfsn19970313@foxmail.com
 * @date 2020-01-08 11:24
 * @notify 解析<insert><select>标签，读取入参，返回值，id等信息,标签内容交给XMLScriptBuilder
 * @version 1.0
 */
public class XMLStatementBuilder {
    private Configuration configuration;

    public XMLStatementBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    //解析标签
    public void parseStatementElement(Element selectElement, String namespace, String sqlType) throws Exception {
        //读取id
        String statementId = selectElement.attributeValue("id");
        //如果id不存在则返回
        if (statementId == null || selectElement.equals("")) {
            return;
        }
        //拼接namespace
        statementId = namespace + "." + statementId;
        //查询 parameterType 属性
        String parameterType = selectElement.attributeValue("parameterType");
        //通过类名获取Class
        Class<?> parameterClass = ResolveType.resolveType(parameterType);
        //查询 resultType 属性
        String resultType = selectElement.attributeValue("resultType");
        Class<?> resultClass = null;
        if (resultType != null && !resultType.equals("")) {
            //通过类名获取Class
            resultClass = ResolveType.resolveType(resultType);
        }

        //获取statementType属性
        String statementType = selectElement.attributeValue("statementType");
        //设置默认的statementType属性
        statementType = statementType == null || statementType == "" ? "prepared" : statementType;
        // 解析SQL信息
        SqlSource sqlSource = createSqlSource(selectElement);


        MappedStatement mappedStatement = new MappedStatement(statementId, parameterClass, resultClass, statementType,
                sqlSource, sqlType);
        //设置Configuration参数
        configuration.addMappedStatement(statementId, mappedStatement);

    }

    //获取sqlSource
    private SqlSource createSqlSource(Element selectElement) throws Exception {
        XMLScriptBuilder xmlScriptBuilder = new XMLScriptBuilder();
        SqlSource sqlSource = xmlScriptBuilder.parseScriptNode(selectElement);
        return sqlSource;
    }


}
